<?php
namespace app\index\pointscontroller;


use think\Request;
use phpException\SuccessException;
use app\index\model\Comments;
use app\index\model\Words;
use phpException\ErrorException;

class Comment
{
	//评论文章
	public function comment_say()
	{
		try{
			$info = \Request::header();
			$token = $info['token'];
			//登录状态才能登录
			if(!token_exists($token)){
				throw new ErrorException('尚未登录博客',401);
			}
			$data = request()->param();

			//调用验证器
			$validate = new \app\index\validate\Commentv;
			//抛出异常
			if (!$validate->check($data)) {
        		throw new ErrorException($validate->getError(),412);
    		}
    		//获取评论者id
    		$uid = \Cache::get($token);

			$words = new Words;
    		$word = $words->get_word($data['word_id']);
    		if(empty($word)) {
    			throw new ErrorException('文章不存在',410);
    		}
    		//添加的数据整合
    		$arr = [
			    'content' =>  $data['content'],
			    'uid'  =>  $uid['id'],
			];
    		//在文章中添加评论
    		$n = $words->add_comment($data['word_id'],$arr);

			if($n){
				throw new SuccessException("评论成功",200);
			} else {
				throw new ErrorException('评论失败',412);
			}
		}catch(Exception $e){
			throw new ErrorException($e);
		}
	}
}